require 'libxml'

class MozarteumController < ApplicationController
  @@a=Array.new
  autocomplete :rismid, :h0001
  def analyze
    require 'libxml'
    dn =''
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/Sm.xml')
    if params[:record]
      rismid=params[:record][:id]
    end
    book_xpath = '//record'
    nodes=xml_document.find(book_xpath)
    @countnodes=nodes.size
    @res={}
    nodes.each {|record| record.each {|node|
        
          tag=node.name
          if !@res.key?(tag)
            @res[tag]=[]
          end       
        
      }
    }
    @endlist=[]
    @res.keys.each{|k| @endlist << k if k}
    @el=@endlist
  end

  def changelog
  end

  def showsubfield
    if params[:subfield]
      @field=params[:subfield]
      xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/Sm.xml')
      book_xpath = '//record/'+String(@field)+'/text()'
      keys=xml_document.find('//record/rarid/text()').to_a 
      values=xml_document.find(book_xpath).to_a
      @nodes=Hash[keys.zip values]
      @countno=@nodes.size if @nodes.size > 0
    end
  end

  def populate
    rismid="B00340000"
    dn ='marc:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/Sm.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//marc:record/marc:controlfield[@tag="001"][contains(.,"'+rismid+'")]/..'
    nodes=xml_document.find(book_xpath,dn)
    #@old_xml=nodes[0]
    #x=Rismid.find(:first, :conditions=>"h0001='B00340000'").xml
    #@old_xml=LibXML::XML::Document.string(x)

    #@ids=xml_document.find('//marc:record/marc:controlfield[@tag="001"]/text()',dn).to_a.select {|s| !s.to_s.start_with?('4')}
    @ids=xml_document.find('//record')
    @ids.each {|r|
      rismid=String(r.find('rarid/text()')[0])      
      xml=r.to_s()
      n=Mozarteum.new(:h0001=>rismid, :xml=>xml)
      n.save
    }
  end

  def hash_to_xml(input_hash, mapper)
    xml=LibXML::XML::Document.new()
    xml.root = LibXML::XML::Node.new("collection")
    xml.root << record=LibXML::XML::Node.new("record")
    record  << field=LibXML::XML::Node.new("leader")
    field.content="00910cdd#a2200253###4500"
    
      if (input_hash['inhalt'].scan /<wid:[0-9]+>/).size>1
        xml=LibXML::XML::Document.new()
             xml.root = LibXML::XML::Node.new("collection")
        xml.root << record=LibXML::XML::Node.new("record")
             record  << field=LibXML::XML::Node.new("leader")
             field.content="00910cdd#a2200253###4500"
             
        record << field=LibXML::XML::Node.new("datafield")
                field['tag']='100'
                field['ind1']=" "
                field['ind2']=" "
                field << sub=LibXML::XML::Node.new("subfield")
                sub['code']='a'
                sub.content='Collection'
      end
        (input_hash['inhalt'].scan /<wid:[0-9]+>/).each{|i|
          mapper.keys.each{|key|
           xml.root << record=LibXML::XML::Node.new("record")
          record << field=LibXML::XML::Node.new("controlfield")
          field['tag']='001'
            field.content=i       
        
        
      if key=='inhalt'
        record << field=LibXML::XML::Node.new("datafield")
                field['tag']="100"
                field['ind1']=" "
                field['ind2']=" "
                field << sub=LibXML::XML::Node.new("subfield")
                sub['code']="a"
                sub.content=input_hash[key].split(":")[0]   
      elsif mapper[key].include?('$')
        df=mapper[key].sub(/\$.*/,"")
        sf=mapper[key].sub(/.*\$/, "")
  record << field=LibXML::XML::Node.new("datafield")
          field['tag']=df
          field['ind1']=" "
          field['ind2']=" "
          field << sub=LibXML::XML::Node.new("subfield")
          sub['code']=sf
          sub.content=input_hash[key]
        elsif mapper[key][0]=='@'
          df=key.sub(/\$.*/,"")
          sf=key.sub(/.*\$/, "")
          record << field=LibXML::XML::Node.new("datafield")
          field['tag']=df
          field['ind1']=" "
          field['ind2']=" "
          field << sub=LibXML::XML::Node.new("subfield")
          sub['code']=sf
          sub.content=mapper[key][1..-1]
        else
          mapper[key][0]=='0'
          record << field=LibXML::XML::Node.new("controlfield")
          field['tag']=mapper[key]
          field.content=input_hash[key]
        end
  }
  }

      
      xml
    end

    
    
   def convertxml(x)
            @old_xml=LibXML::XML::Document.string(x).root
            #@url=String(@old_xml.find('datafield[@tag="856"]/subfield[@code="u"]/text()')[0])
            converter=MarcTools::MarcConverter.new
            @marc_hash=converter.xml_to_hash(@old_xml)
            @marc_hash=converter.insertTag(@marc_hash, '000leader', '')
            @marc_hash=converter.insertTag(@marc_hash,'001', (659300000+(@marc_hash['rarid']).to_i).to_s)
            if not @marc_hash['inhalt'].start_with?("[")
              composer_long=@marc_hash['inhalt'].gsub(/\n.+/, "").gsub(/\:.*$/,"").strip
              title_long=@marc_hash['inhalt'].gsub(/\n/, "").sub(/^.*?\:/, "").strip
              wid=title_long.gsub(/^.*wid:/,"").gsub(/\>/, "")
            else
              composer_long=@marc_hash['inhalt'].sub(/^\[.*\]/, "").gsub(/\n.+/, "").gsub(/\:.*$/,"").strip
              title_long=@marc_hash['inhalt'].gsub(/\n/, "").sub(/^.*?\:\]/, "").strip
              wid=title_long.gsub(/^.*wid:/,"").gsub(/\>/, "")
            end
            composer_name=composer_long.sub(/\(.+/, "").strip              
            composer_date=composer_long.sub(/.+\(/, "").gsub(")","").strip

            @marc_hash=converter.insertTag(@marc_hash,'100$a', composer_name)
            @marc_hash=converter.insertTag(@marc_hash,'100$d', composer_date) if composer_date.match(/[0-9]/)
            @marc_hash=converter.insertTag(@marc_hash,'240$a', title_long)
            @marc_hash=converter.insertTag(@marc_hash,'245$a', @marc_hash['titeltxt'].gsub(/\n/, " "))
            @marc_hash=converter.insertTag(@marc_hash,'260$c', @marc_hash['abschrdat']) if @marc_hash['abschrdat'].size > 1
            @marc_hash=converter.insertTag(@marc_hash,'300$c', @marc_hash['format']) if @marc_hash['format'].size > 1
            @marc_hash=converter.insertTag(@marc_hash,'300$a', @marc_hash['material'])
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "WID: "+wid)
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "Besitzvermerk: "+@marc_hash['besitzvermerk']) if @marc_hash['besitzvermerk'].size > 1
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "Herkunft: "+@marc_hash['herkunft'])
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "Invnr: "+@marc_hash['invnr']) if not @marc_hash['invnr'].include?("NULL")
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "Digifilepattern: "+@marc_hash['digifilepattern']) if @marc_hash['digifilepattern'].size > 1
            @marc_hash=converter.insertTag(@marc_hash,'500$a', "Anmerkung: "+@marc_hash['anmerkung']) if not @marc_hash['anmerkung'].include?('NULL') and @marc_hash['anmerkung'].size>1
            @marc_hash=converter.insertTag(@marc_hash,'561$a', @marc_hash['sammlung']) if @marc_hash['sammlung'].size > 1
            @marc_hash=converter.insertTag(@marc_hash,'591$a', @marc_hash['alte_signatur']) if @marc_hash['alte_signatur'].size > 1
            if @marc_hash['schreiber'].size>1
              @marc_hash=converter.insertTag(@marc_hash,'700$a', @marc_hash['schreiber']) if not @marc_hash['schreiber'].include?('Autograph')
              @marc_hash=converter.insertTag(@marc_hash,'700$4', "scr") if not @marc_hash['schreiber'].include?('Autograph')
            end
            @marc_hash=converter.insertTag(@marc_hash,'593$a', @marc_hash['schreiber']) if @marc_hash['schreiber'].include?('Autograph')
            @marc_hash=converter.insertTag(@marc_hash,'852$a', 'A-Sm')
            @marc_hash=converter.insertTag(@marc_hash,'852$c', @marc_hash['signatur'])
            #@marc_hash=converter.changeSubfieldCode(@marc_hash,'650$3', '650$a')
          #@marc_hash=converter.moveTag(@marc_hash,'240$n', '240$a')
          #@marc_hash=converter.moveTag(@marc_hash,'300$c', '300$a')
          #@marc_hash=converter.removeTagbyValue(@marc_hash,'700$a', 'unbekannt')
          #@marc_hash=converter.removeTagbyValue(@marc_hash,'657$y', 'unbekannt')
          @new_xml=converter.hash_to_marc(@marc_hash)
          end
    
  
      
    
    def convert
      require 'MarcTools'   
      mapper={"rarid"=>"001", "titeltxt"=>"245$a", "inhalt"=>nil}
          rismid="1706"
          if params["record"]
            rismid=params["record"]["rismid"]
          end
          @params=params
          x=Mozarteum.find(:first, :conditions=>"h0001='"+rismid+"'")
          if x
            x=x.xml
          convertxml(x)

        end
        end


    def retrieveFile
      require 'MarcTools'
          #rismid="B00340000"
          x=Mozarteum.find(:all)
        xml=LibXML::XML::Document.new()
        xml.root = LibXML::XML::Node.new("collection")                  
 
        #x=Rismid.find(:first, :conditions=>"h0001='"+rismid)
        x.each {|tempxml| 
        new_xml=convertxml(tempxml.xml)
        p new_xml
          a=xml.import(new_xml.root.child)
            xml.root << a
          #xml.root << new_xml.root.child
          }
    xml.save('mozarteum_out.xml', :indent => true, :encoding => LibXML::XML::Encoding::UTF_8)      
 
=begin          

          tempxmlx=tempxml.xml

          @old_xml=LibXML::XML::Document.string(tempxml).root
        @url=String(@old_xml.find('datafield[@tag="856"]/subfield[@code="u"]/text()')[0])
        converter=MarcTools::MarcConverter.new
        @marc_hash=converter.marc_to_hash(@old_xml)
        @marc_hash=converter.changeSubfieldCode(@marc_hash,'650$3', '650$a')
        @marc_hash=converter.moveTag(@marc_hash,'240$n', '240$a')
        @marc_hash=converter.moveTag(@marc_hash,'300$c', '300$a')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'700$a', 'unbekannt')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'657$y', 'unbekannt')
        @new_xml=converter.hash_to_marc(@marc_hash)
        p @new_xml
=end
        
      end












  def test 
    if ((params["commit"]).to_s == "Reset") 
      @@a=Array.new 
    end
    @x = (params["Rechne!"]["Aufgabe"]).to_s    
    @result=eval(@x)   
    @@a.push((Array.new).push(@result).push(@x))
    @a=@@a.reverse 
  end



end

